# bet365 websocket 客户端实现
from pprint import pprint

from requests import request
from ws4py.client.threadedclient import WebSocketClient
import time
import random

def log(s):
    print('[%s]'%time.strftime("%Y-%m-%d %H:%M:%S"), s)

def get_uid():
    return f'{random.random()}'[2:]

class WebSockets(WebSocketClient):

    # _URLS_CONNECTION = 'wss://premws-pt1.365lpodds.com/zap/'

    _URLS_CONNECTION = f'wss://premws-pt3.365pushodds.com/zap/?uid={get_uid()}'
    _URLS_SESSION_ID = 'https://www.348365365.com/#/IP/'


    _HEADERS = [
        ('Sec-WebSocket-Extensions', 'permessage-deflate; client_max_window_bits'),
        ('Sec-WebSocket-Protocol', 'zap-protocol-v1'),
        ('Sec-WebSocket-Version', '13'),
        ('Host','premws-pt3.365pushodds.com'),
        ('Origin','https://www.348365365.com'),
        ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'),
        ('Accept-Encoding','gzip, deflate, br'),
        ('Accept-Language','zh-CN,zh;q=0.9'),
        ('Cache-Control','no-cache'),
        ('Connection', 'Upgrade'),
    ]

    _DELIMITERS_RECORD = u'\x01'
    _DELIMITERS_FIELD = u'\x02'
    _DELIMITERS_HANDSHAKE = '\x03'
    _DELIMITERS_MESSAGE = u'\x08'

    _ENCODINGS_NONE = u'\x00'

    _TYPES_TOPIC_LOAD_MESSAGE = u'\x14'
    _TYPES_DELTA_MESSAGE = u'\x15'
    _TYPES_SUBSCRIBE = u'\x16'
    _TYPES_PING_CLIENT = u'\x19'
    _TYPES_TOPIC_STATUS_NOTIFICATION = '#'

    #P__time,S_8AC8E570DD394663AD766B96C39845AC000003

    _TOPICS = [
        'CONFIG_10_0,OVInPlay_10_0,Media_L10_Z0,XL_L10_Z0_C1_W3',
        # '__host',
        # 'CONFIG_1_3',
        # 'XL_L1_Z3_C1_W4',
        # 'HL_L1_Z3_C1_W4',
        # 'InPlay_1_3',
        # 'LHInPlay_1_3',
        # 'Media_l1_Z3',
        # 'OVInPlay_10_0',
        # 'XI_1_3',
        # 'CONFIG_10_0','OVInPlay_10_0','Media_L10_Z0','XL_L10_Z0_C1_W3','6V73430610C1A_10_0','LT_1_10_0',
        # '6V76895064C18A_10_0,1565026545M18_10_0',
        # 'CONFIG_10_0,OVInPlay_10_0,Media_L10_Z0,XL_L10_Z0_C1_W3'
    ]

    # 6V76895064C18A_10_0,1565026545M18_10_0

    # 第一次握手
        # 发送给服务端：      #P__time,S_090878C4A1734BF59DF2789215B70CB4000003
        # 服务端返回：        100IRUD06-f3H6e2WzMwRw


    _MESSAGES_SESSION_ID = u'%s%sP%s__time,S_%%s%s' % (
        _TYPES_TOPIC_STATUS_NOTIFICATION,
        _DELIMITERS_HANDSHAKE,
        _DELIMITERS_RECORD,
        _ENCODINGS_NONE,
    ) # 第一次握手发给服务端

    _MESSAGES_SUBSCRIPTION = u'%s%s%%s%s' % (
        _TYPES_SUBSCRIBE,
        _ENCODINGS_NONE,
        _DELIMITERS_RECORD,
    )

    _GET_MESSAGES = u'%scommand%sgetMessage%s%%s%sSPTBK%s10' % (
        _DELIMITERS_FIELD,
        _DELIMITERS_RECORD,
        _DELIMITERS_RECORD,
        _DELIMITERS_FIELD,
        _DELIMITERS_FIELD,
        )

    def __init__(self):
        print(self._URLS_CONNECTION)
        super(WebSockets, self).__init__(self._URLS_CONNECTION, headers=self._HEADERS)
        self.session_id = ''

    def connect(self):
        print('opening connection...')
        super(WebSockets, self).connect()

    def disconnect(self):
        print('closing connection...')

    def opened(self):
        print('opened connection')
        self.session_id = self._fetch_session_id()
        # self.session_id = '4E0A42DBFA5951418F991DDE2E73BD7C000003'
        if not self.session_id:
            self.disconnect()
            return
        message = self._MESSAGES_SESSION_ID % self.session_id
        self._send(message)
        print(message)

    def closed(self, code, reason=None):
        print('closed connection')
        print('code:', code)
        print('reason:', reason)

    def received_message(self, message):
        # message = message.encode('utf-8')
        # print(dir(message))
        if message.is_text:
            try:
                message = message.data.decode('utf-8')
            except Exception as e:
                print(e)
        else:
            pass
        print('↓↓↓: %s'%message)
        message = message.split(self._DELIMITERS_MESSAGE)
        while 1:


            a = message.pop()
            b = a[0]
            if b == '1':
                for topic in self._TOPICS:
                    m = self._MESSAGES_SUBSCRIPTION % topic

                    self._send(m)
                # self._send(self._GET_MESSAGES % self.session_id)
                # continue
            if b in [self._TYPES_TOPIC_LOAD_MESSAGE, self._TYPES_DELTA_MESSAGE]:
                matches = a.split(self._DELIMITERS_RECORD)
                path_config = matches[0].split(self._DELIMITERS_FIELD)
                pair = path_config.pop()
                read_it_message = pair[1:]
                l = a[(len(matches[0]) + 1):]
                # pprint([read_it_message, l], width=1)
                continue

    def _send(self, message):
        print('↑↑↑:', repr(message))
        self.send(message)

    def _fetch_session_id(self):
        print('fetching session id...')
        response = None
        try:
            response = request(method='GET', url=self._URLS_SESSION_ID, timeout=5)
        except Exception:
            pass
        if not response:
            print('session id: N/A')
            return
        session_id = response.cookies['pstk']
        print('session id:', session_id)
        return session_id


if __name__ == '__main__':
    try:
        web_sockets = WebSockets()
        web_sockets.connect()
        web_sockets.run_forever()
    except KeyboardInterrupt:
        web_sockets.disconnect()